package com.qiaoyanqing.ximalaya.util;

import android.os.Handler;
import android.os.Message;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by softpo on 2016/9/30.
 */
public class MyOkHttpUtils {
    public static void getNetData(final String path, final Handler handler) {

        new Thread(){
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();

                Request.Builder builder = new Request.Builder();

                builder.url(path);

                builder.build();

                Request request = builder.build();

                try {
                    Response response = client.newCall(request).execute();

                    //判断联网成功
                    if(response.isSuccessful()){
                        ResponseBody body = response.body();

                        byte[] data = body.bytes();

                        String result = new String(data,"UTF-8");

                        Message message = handler.obtainMessage();

                        message.what = 1;

                        message.obj = result;

                        handler.sendMessage(message);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();


    }

    public static byte[] getByteFromUrl(String path){
        byte[] ret = null;
        OkHttpClient client= new OkHttpClient();

        Request.Builder builder = new Request.Builder();

        builder.url(path);

        Request request = builder.build();

        try {
            Response response= client.newCall(request).execute();

            if(response.isSuccessful()){

                ret = response.body().bytes();

            }

        } catch (IOException e) {
            e.printStackTrace();
        }


        return  ret;
    }
}
